package com.caifeng.myapplication.fragment;

import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.caifeng.myapplication.R;

public class DemoFragment extends AppCompatActivity {

    private FrameLayout frameLayout;
    OneF oneF;
    TwoF twoF;
    RadioGroup rg;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

        getFragment();
        frameLayout = findViewById(R.id.f1);
        rg = findViewById(R.id.rg);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.one:
                        hideFragment(twoF);
                        showFragment(oneF);
                        break;
                    case R.id.two:
                    hideFragment(oneF);
                    showFragment(twoF);
                    break;
                }
            }
        });

    }

    private void getFragment() {
        oneF = new OneF();
        twoF = new TwoF();

        addFragment(oneF);
        addFragment(twoF);

        hideFragment(oneF);
        hideFragment(twoF);

        showFragment(oneF);


    }

    private void addFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.f1, fragment);
        fragmentTransaction.commit();

    }

    private void showFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().show(fragment).commit();
    }

    private void hideFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().hide(fragment).commit();
    }


}
